<?php namespace sacvoyage\storage;

require_once("sacvoyage/util.php");
use sacvoyage\exception\InternalException;
use \mysqli as mysqli;

/*
 * represents connection to mysql-database
 *
 */
class Gateway {


	public function __construct($host, $db, $user, $password) {
		$this->_connection=new mysqli($host, $user, $password, $db);
		if(mysqli_connect_errno()!=0) {
			throw new Exception("connection to database failed: \n". mysqli_connect_error());
		}
	}	
	
	public function __destruct() {
		$this->_connection->close();
	}

	public function getTableNames() {
		$tables=array();
		$result=$this->query('SHOW TABLES');
		while($row=$result->fetch_row()) { 
			$tables[]=$row[0]; 
		}
		$result->free();
		return $tables;
	}

	public function generateTableName($desired, $prefix='', $postfix='') {
		$tableNames=$this->getTableNames();
		if(is_safe_name($desired) && !in_array($desired, $tableNames)) {
			return $desired;
		}
		do {
			$try=$prefix.random_string().$postfix;
		} while(in_array($try, $tableNames));
		return $try;
	}

	public function query($sql, $errorMessage=null) {
		$result=$this->_connection->query($sql);
		if(!$result) {
			if($errorMessage===null) {
				$errorMessage="error executing query";
			}
			throw new InternalException("$errorMessage: {$this->_connection->error}\n$sql");
		}
		return $result;
	}

	public function escape($string) {
		return $this->_connection->real_escape_string($string);
	}

	public function getAffectedRows() {
		return $this->_connection->affected_rows;
	}
	
	private $_connection;
	private $_tables;
	private static $_default=null;	
}




?>
